// import {ajax_tool, myDebounce, changObj} from './common.js';
import {sessionTime, appointmentTime, sessionRecord, timeList} from './request.js';

let data = document.querySelector('.data');
let dateList = document.querySelector('.dateList');
let session = document.querySelector('.session');
let masking = document.querySelector('.masking');
let details = document.querySelector('.details');
let tiemList = document.querySelector('.tiemList');
let btns = document.querySelectorAll('.btns button');
// console.log(details);
// 获取当前日期，渲染上页面
let dateTime = new Date();
data.firstElementChild.firstElementChild.innerHTML = `${dateTime.getMonth() + 1}月${dateTime.getDate()}日`;
// 给月份补零
let monthDate = dateTime.getMonth() + 1 < 10 ? "0" + (dateTime.getMonth() + 1) : dateTime.getMonth() + 1;
let data_Time = `${dateTime.getFullYear()}-${monthDate}-${dateTime.getDate()}`;
data.firstElementChild.firstElementChild.setAttribute('data-time', data_Time);


// 点击下拉按钮显示日期列表
data.children[0].addEventListener('click', function() {
    // console.log(this.nextElementSibling);
    this.nextElementSibling.className = 'dateList showList';
});


dateFn();
// ajax请求时间列表,并渲染
async function dateFn() {
    let obj = new Object({token: sessionStorage.getItem('token')});
    // ajax请求时间列表
    let data1 = await timeList(obj);
    let num = 0;
    // 清空时间列表
    dateList.firstElementChild.innerHTML = "";
    // 渲染时间列表
    data1.result.list.forEach(function(item) {
        num++;
        dateList.firstElementChild.innerHTML += `
                                                <li data-time="${item.day_time}">
                                                    <label for="time${num}">
                                                        ${item.day_time}
                                                        <input type="radio" name="dateTiem" id="time${num}" data-time="${item.day_time}">
                                                    </label>
                                                </li>
                                                `
    })
    let liList = document.querySelectorAll('.dateList ul li');
    // 选择预约日期，选中后隐藏列表
    liList.forEach(function(item) {
        item.addEventListener('click', function() {
            // 加载动画
            masking.className = 'masking loading';
            // 把选中的日期渲染上表头
            data.firstElementChild.firstElementChild.setAttribute('data-time', item.getAttribute("data-time"));
            data.firstElementChild.firstElementChild.innerHTML = `${new Date(item.getAttribute("data-time")).getMonth() + 1}月${new Date(item.getAttribute("data-time")).getDate()}日`;
            // 隐藏时间列表
            dateList.className = "dateList"; 
            // 请求选中日期的场次，并渲染
            let obj = {};
            obj.token = sessionStorage.getItem('token');
            obj.day_time = data.firstElementChild.firstElementChild.getAttribute("data-time");
            // ajax请求
            timeData(obj);
        })
    })
    console.log(data1.result.list);
}


// 页面加载完之后，渲染当天预约时间
window.addEventListener('load', function(e) {
    let obj = {};
    obj.token = sessionStorage.getItem('token');
    obj.day_time = data.firstElementChild.firstElementChild.getAttribute('data-time');
    timeData(obj);
})


// 请求预约记录
async function recordArr() {
    let obj = {};
    obj.phone = sessionStorage.getItem('phone');
    obj.name = sessionStorage.getItem('name');
    // ajax请求预约记录
    let timeRecord = await  sessionRecord(obj);
    return timeRecord;
};


// 请求数据，并渲染数据
async function timeData(obj) {
    // ajax请求预约记录
    let timeRecord = await recordArr();
    console.log(timeRecord);
    // 筛选出选中的日期预约记录
    let  cecord_arr = [];
    timeRecord.result.forEach(function(item) {
        // if (new Date(item.day_time).getTime() == new Date(obj.day_time).getTime()) {
            cecord_arr.push(item.day_time);
        // }
    })
    console.log(cecord_arr);


    // ajax请求场次
    let data = await sessionTime(obj);
    // 数据回来后清除动画
    masking.className = 'masking';
    // console.log(data);
    // 数据回来前，先清除之前的时间
    session.lastElementChild.innerHTML = "";
    // 获取预约时间段
    let times = data.result.list;
    console.log(times);
    times.forEach(function(item) {

        // 下面是预约时间
        let newTime = new Date(item.day_time);
        // 月
        let dateMonth = newTime.getMonth();
        // 日
        let dateStr = newTime.getDate();
        // 时
        let hoursStr = String(item.show_name).slice(6, 8);
        // console.log(hoursStr);
        // 场次的时间戳
        let timestamp = new Date(`2021-${dateTime.getMonth() + 1}-${dateTime.getDate()}  ${hoursStr}:00:00`).getTime();

        // 判断时间戳，确定场次是否可以预约
        // console.log(timestamp);
        if (dateTime.getMonth() == dateMonth && dateTime.getDate() < dateStr || dateTime.getMonth() < dateMonth) {
            if (!cecord_arr.includes(item.day_time)) {
                // console.log(item.show_id.toString());
                session.lastElementChild.innerHTML += `
                                            <li>
                                                <span>${item.show_name}</span>
                                                <span class='btn'  data-time="${item.day_time}" data-id="${item.show_id}">可预约</span>
                                            </li>
                                            `
            } else {
                session.lastElementChild.innerHTML += `
                                            <li>
                                                <span>${item.show_name}</span>
                                                <span class='past'  data-time="${item.day_time}" data-id="${item.show_id}">今日已预约</span>
                                            </li>
                                            `
            }
        } else {
            // console.log(dateTime.getTime());
            if (!cecord_arr.includes(item.day_time)) {
                if (dateTime.getTime() < timestamp) {
                    console.log('1');
                    session.lastElementChild.innerHTML += `
                                                    <li>
                                                        <span>${item.show_name}</span>
                                                        <span class='btn' data-time="${item.day_time}" data-id="${item.show_id}">可预约</span>
                                                    </li>
                                                    `
                } else {
                    session.lastElementChild.innerHTML += `
                                                    <li>
                                                        <span>${item.show_name}</span>
                                                        <span class='past'>已结束</span>
                                                    </li>
                                                    `
                }
            } else {
                session.lastElementChild.innerHTML += `
                                            <li>
                                                <span>${item.show_name}</span>
                                                <span class='past'  data-time="${item.day_time}" data-id="${item.show_id}">今日已预约</span>
                                            </li>
                                            `
            }
        }
    });
    // 获取可预约的按钮
    let buttons = document.querySelectorAll(".btn");
    // 执行点击预约按钮的函数
    detailsFn(buttons);
    // console.log(button);
}

// 点击预约按钮的函数
function detailsFn(btns) {
    btns.forEach(function(item) {
        item.addEventListener('click', function() {
            // 时间
            let time = new Date(this.getAttribute('data-time'));
            // 年
            let year = time.getFullYear();
            // 月
            let month = time.getMonth() + 1 < 10 ? "0" + (time.getMonth() + 1) : (time.getMonth() + 1);
            // 日
            let date = time.getDate();
            // 渲染预约时间
            tiemList.innerHTML = `
                                <li data-id="${this.getAttribute('data-id')}">日期：${year}-${month}-${date}</li>
                                <li>时间：${item.previousElementSibling.innerHTML}</li>
                                `
            // 弹出详情框
            details.className = 'details showDetails';
            // console.log(year, month, date);
        });
    });
}

// 点击确定预约函数
btns[1].addEventListener('click', function() {
    // 收回详情框
    details.className = 'details';
    // 显示加载动画
    masking.className = 'masking loading';
    let obj = {};
    obj.token = sessionStorage.getItem('token');
    obj.day_time = data.firstElementChild.firstElementChild.getAttribute('data-time');
    obj.show_id = tiemList.firstElementChild.getAttribute("data-id");
    session_data(obj);
    console.log(obj);
})

// 发送预约某天场次的请求
async function session_data(obj) {
    // ajax预约请求
    let data = await appointmentTime(obj);
    // 隐藏动画
    masking.className = 'masking';
    sessionStorage.setItem('day_time', data.result.day_time);
    sessionStorage.setItem('id', data.result.id);
    sessionStorage.setItem('show_id', data.result.show_id);
    console.log(data);
    location.href = `verifyCode.html`;
}

// 点击取消预约函数
btns[0].addEventListener('click', function() {
    // 隐藏详情框
    details.className = 'details';
})